package com.rad.ip.discovery.service.impl;

import com.orbitz.consul.Consul;
import com.orbitz.consul.model.agent.ImmutableRegistration;
import com.orbitz.consul.model.agent.Registration;
import com.rad.base.model.Result;
import com.rad.ip.discovery.dao.IpEntryMapper;
import com.rad.ip.discovery.model.IpEntry;
import com.rad.ip.discovery.service.IpEntryService;
import com.rad.ip.discovery.core.AbstractService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;


/**
 * Created by CodeGenerator on 2018/05/21.
 */
@Service
@Transactional
public class IpEntryServiceImpl extends AbstractService<IpEntry> implements IpEntryService {
    private Logger logger = LoggerFactory.getLogger(IpEntryServiceImpl.class);
    @Resource
    private IpEntryMapper ipEntryMapper;
    @Resource
    private Consul client;
    @Value("${ip-discovery.export.name-prefix}")
    private String namePrefix;
    @Value("${ip-discovery.export.api}")
    private String api;
    @Value("${ip-discovery.export.target}")
    private String target;
    @Value("${ip-discovery.export.port}")
    private int port;


    @Override
    public Result saveIp(String serviceId,String ip) {
        IpEntry ipEntry = ipEntryMapper.selectByPrimaryKey(serviceId);
        if(ipEntry!=null){
            logger.info("已注册的serviceId，{}，ip:{}",serviceId,ip);
            logger.info("查询数据库中记录:{}",ipEntry);
            if(!ip.equals(ipEntry.getIpAddress())){
                logger.info("修改注册服务的ip");
                try {
                    rIp(serviceId,ip);
                    ipEntry.setIpAddress(ip);
                    logger.info("数据库修改{}的ip为{}",serviceId,ip);
                    int i = ipEntryMapper.updateByPrimaryKeySelective(ipEntry);
                    logger.info("修改结果{}",i);
                    if(i>0){
                        return Result.success(i);
                    }else{
                        return Result.exception("500","修改失败");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    return Result.exception("500","远程服务修改失败");
                }
            }else{
                logger.info("ip无变化，无需修改");
                return Result.success("ok");
            }
        }else{//未注册的serviceId及IP
            logger.info("未注册的serviceId，{}，ip:{}",serviceId,ip);
            ipEntry = new IpEntry();
            ipEntry.setServiceId(serviceId);
            ipEntry.setIpAddress(ip);
            logger.info("新注册service服务：{}",ipEntry);
            try {
                logger.info("注册服务到consul");
                rIp(serviceId,ip);
                int i = ipEntryMapper.insert(ipEntry);
                logger.info("添加注册的服务记录到数据库：{}",i);
                if(i>0){
                    return Result.success(i);
                }else{
                    return Result.exception("500","添加失败");
                }
            }catch (Exception e){
                e.printStackTrace();
                return Result.exception("500","远程服务注册失败");
            }
        }
    }

    @Override
    public Result setIp(String serviceId, String ip) {
        IpEntry ipEntry = ipEntryMapper.selectByPrimaryKey(serviceId);
        if(ipEntry!=null){
            logger.info("已注册的serviceId，{}，ip:{}",serviceId,ip);
            logger.info("查询数据库中记录:{}",ipEntry);
            if(!ip.equals(ipEntry.getIpAddress())){
                ipEntry.setIpAddress(ip);
                logger.info("数据库修改{}的ip为{}",serviceId,ip);
                int i = ipEntryMapper.updateByPrimaryKeySelective(ipEntry);
                logger.info("修改结果{}",i);
                if(i>0){
                    return Result.success(i);
                }else{
                    return Result.exception("500","修改失败");
                }
            }else{
                logger.info("ip无变化，无需修改");
                return Result.success("ok");
            }
        }else{//未注册的serviceId及IP
            logger.info("未注册的serviceId，{}，ip:{}",serviceId,ip);
            ipEntry = new IpEntry();
            ipEntry.setServiceId(serviceId);
            ipEntry.setIpAddress(ip);
            logger.info("新注册service服务：{}",ipEntry);
            int i = ipEntryMapper.insert(ipEntry);
            logger.info("添加注册的服务记录到数据库：{}",i);
            if(i>0){
                return Result.success(i);
            }else{
                return Result.exception("500","添加失败");
            }
        }
    }

    //查询已有的服务
    private void selIpMap(){
        Map<String, com.orbitz.consul.model.health.Service> services = client.agentClient().getServices();
        for (Map.Entry<String, com.orbitz.consul.model.health.Service> entry : services.entrySet()) {
            System.out.println("key:" + entry.getKey());
            System.out.println("value:" + entry.getValue().toString());
        }
    }

    //注册服务
    private void rIp(String serviceId,String ip){
        String serviceName = namePrefix+serviceId;
        Registration.RegCheck single = Registration.RegCheck.http("http://"+ip+api, 20);
        Registration reg = ImmutableRegistration.builder()
                .check(single)
                .addTags(target)
                .address(ip)
                .port(port)
                .name(serviceName)
                .id(serviceId)
                .build();
        client.agentClient().register(reg);
    }
}
